home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 3138 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  2.3 KB

  1. Path: dawn.mmm.com!news
  2. From: kjhopps@mmm.com (Kevin J Hopps)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: void pointers
  5. Date: 22 Jan 1996 13:47:47 GMT
  6. Organization: 3M - St. Paul, MN  55144-1000 US
  7. Message-ID: <4e04i3$ete@dawn.mmm.com>
  8. References: <Pine.SUN.3.91.960105113409.18158A-100000@phoenix.acms.arizona.edu> <DKx5H9.1rF@news.zippo.com>
  9. Reply-To: kjhopps@mmm.com
  10. X-Newsreader: TIN [version 1.2 PL2]
  11.  
  12. Jim McFarland (jgm6@orkand.em.cdc.gov) wrote:
  13. > Kenton White <jwhite@phoenix.acms.arizona.edu> wrote:
  14. > >
  15. > >
  16. > >I am trying to create a class that stores pointers to other classes in an
  17. > >array of void pointers.  Since void pointers cannot be dereferenced, is
  18. > >there any way to cast the void pointer to a non-void pointer and then
  19. > >dereference? 
  20. > >
  21. > You are trying to use a very C-oriented solution, instead of taking 
  22. > advantage of the power of object-oriented programming offered by C++.  
  23. > What you are trying to create is a container class.  Your compiler may 
  24. > already provide a class that will do this.  If not, you should use 
  25. > polymorphism to create a container that can contain pointers to various 
  26. > classes, without needing to use void pointers.  To do this, your classes 
  27. > will need to have a common base class.
  28.  
  29. When creating a template container class it might be good to encapsulate
  30. behavior common to all template instantiations into a single base class
  31. that operates on void pointers.  This helps alleviate some of the code-
  32. bloat that naive use of templates can cause.  In cases like these, using
  33. void pointers may be advantageous.
  34.  
  35. Yes, it is quite possible to cast void pointers to non-void pointers.
  36. In the old syntax, for example:
  37.     T* Container<T>::next()
  38.     {
  39.     void* item = Base::next();
  40.     return (T*)item;
  41.     }
  42. I believe the new syntax would be:
  43.     return reinterpret_cast<T*>(item);
  44.  
  45. OTOH, it's hard to justify inventing container classes these days,
  46. except perhaps for educational purposes, since there are so many class
  47. libraries around.
  48. --
  49. Kevin J. Hopps                  e-mail: kjhopps@mmm.com
  50. 3M Company                      phone:  (612) 737-4643
  51. 3M Center, Bldg. 235-2D-57      fax:    (612) 737-2700
  52. St. Paul, MN 55144-1000         Opinions are my own.  I don't speak for 3M.
  53.     But 3M speaks for me -- I did not write the following line:
  54.  
  55. Opinions expressed herein are my own and may not represent those of 3M.
  56.